package com.wwy.service;

import com.alibaba.fastjson.JSONObject;
import com.wwy.*;
import com.wwy.domain.FiltrationTimeEntiry;
import com.wwy.domain.LabelEntity;
import com.wwy.domain.RssiEntity;
import com.wwy.domain.TypeEntity;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

import static com.wwy.FiltrationTimeDialog.filtrationTimeEntiry;


/**
 * @Author: wwy
 * @Date: 2020/8/14 12:35
 */
@Service
public class MacDataService {
    public static boolean status = false;
    private ConcurrentHashMap<String,Vector> dataMap = new ConcurrentHashMap<>();
    /**
     * 网关数据处理
     * @param message
     */
    public void updateData(Message<?> message){
        FiltrationTimeEntiry filtrationTimeEntiry = FiltrationTimeDialog.filtrationTimeEntiry;
        RssiEntity rssiEntity = RssiDialog.rssiEntity;
        if(rssiEntity.getEnd() ==0){
            rssiEntity.setEnd(-100);
        }
        if(!status){
            return;
        }
        DefaultTableModel defaultTableModel;

        //主题
        String topic = String.valueOf(message.getHeaders().get("mqtt_receivedTopic"));
        //根据主题获取类型id
        List<LabelEntity> labelEntityList = LabelDialog.labelEntityList;
        List<TypeEntity> typeEntityList = TypeDialog.typeEntityList;
        String lableId = "";
        for (LabelEntity labelEntity : labelEntityList) {
            String subScribeName = labelEntity.getSubScribeName();
            if(subScribeName.equals(topic)){
                lableId = labelEntity.getLableId();
                break;
            }
        }
        String typeName = "";
        for (TypeEntity typeEntity : typeEntityList) {
            String id = typeEntity.getId();
            if(id.equals(lableId)){
                typeName = typeEntity.getTypeName();
                break;
            }
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        defaultTableModel = LabelPanel.modelMap.get(lableId);
        JTable table = LabelPanel.tableMap.get(lableId);
        String payload = String.valueOf(message.getPayload());
        List<Map> list = JSONObject.parseObject(payload, List.class);
        for (Map map : list) {
            String bleName = String.valueOf(map.get("bleName"));//名称，没有名称的不要
            /*if(bleName == null || "".equals(bleName)){
                break;
            }*/
            String rawData = String.valueOf(map.get("rawData"));
            if(rawData == null || "".equals(rawData) || "null".equals(rawData)){
                continue;
            }
            String rawDataSub = rawData.substring(0, 6);
            if(!rawDataSub.equals("020106")){
                continue;
            }
            String mac = String.valueOf(map.get("mac"));//mac地址
            String timestamp = String.valueOf(map.get("timestamp"));
            String dateTime = "";
            //时间格式处理
            if(timestamp != null && !"null".equals(timestamp)){

                try {
                    Date parse = simpleDateFormat.parse(timestamp);
                    dateTime = simpleDateFormat1.format(parse);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            String rssi = String.valueOf(map.get("rssi"));
            if(rssi != null && !"".equals(rssi) && !"null".equals(rssi) ){
                int rssiInt = Integer.parseInt(rssi);
                if(rssiInt<=rssiEntity.getEnd() || rssiInt>=rssiEntity.getStart()){
                    return;
                }
                Vector vector = new Vector();
                vector.add(typeName);
                vector.add(topic);
                vector.add(rssi);
                vector.add(mac);
                vector.add(dateTime);
                Vector dataVector = dataMap.get(mac);
                if(filtrationTimeEntiry.getTime() != 0){
                    if(dataVector == null){
                        dataMap.put(mac,vector);
                    }else{
                        int rssiVector = Integer.parseInt(String.valueOf(dataVector.get(2)));
                        if(rssiVector<Integer.parseInt(rssi)){
                            dataMap.put(mac,vector);
                        }
                    }
                }

                if(filtrationTimeEntiry.getTime() == 0){
                    defaultTableModel.addRow(vector);
                    int rowCount = table.getRowCount();
                    table.getSelectionModel().setSelectionInterval(rowCount-1,rowCount-1);
                    Rectangle cellRect = table.getCellRect(rowCount-1, 0, true);
                    table.scrollRectToVisible(cellRect);
                }

            }

        }
    }

    /**
     * 规定时间内执行
     * 1.采用while循环，一直监听
     *  每次睡眠1秒，进行间隔时间的控制，毫秒 = 次数
     *
     */
    public void timerData(){
        int count = 0;
        int time = 0;


        while(true){
            if(filtrationTimeEntiry != null){
                time = filtrationTimeEntiry.getTime();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(!status){
                continue;
            }
            if(time == 0){
                continue;
            }
            //达到指定的秒之后
            if(count >= time){
                //初始化count;
                count = 0;
                for (Map.Entry<String, Vector> stringVectorEntry : dataMap.entrySet()) {
                    String mac = stringVectorEntry.getKey();
                    Vector vectorValue = stringVectorEntry.getValue();
                    //根据主题获取类型id
                    List<LabelEntity> labelEntityList = LabelDialog.labelEntityList;
                    List<TypeEntity> typeEntityList = TypeDialog.typeEntityList;
                    String lableId = "";
                    for (LabelEntity labelEntity : labelEntityList) {
                        String subScribeName = labelEntity.getSubScribeName();
                        if(subScribeName.equals(vectorValue.get(1))){
                            lableId = labelEntity.getLableId();
                            break;
                        }
                    }
                    DefaultTableModel defaultTableModel = LabelPanel.modelMap.get(lableId);
                    JTable table = LabelPanel.tableMap.get(lableId);
                    defaultTableModel.addRow(vectorValue);
                    int rowCount = table.getRowCount();
                    table.getSelectionModel().setSelectionInterval(rowCount-1,rowCount-1);
                    Rectangle cellRect = table.getCellRect(rowCount-1, 0, true);
                    table.scrollRectToVisible(cellRect);

                }
                //初始化
                dataMap = new ConcurrentHashMap<>();
            }

            count ++;
        }
    }
}
